<template>
  <j-editable-table
     ref="mmStockTransferDetail"
    :loading="loading"
    :columns="columns"
    :dataSource="dataSource"
    :maxHeight="300"
    :disabled="false"
    :rowNumber="true"
    :rowSelection="false"
    :actionButton="false"
    @valueChange="qtyAndPriceChange"/>
</template>

<script>

import {FormTypes} from '@/utils/JEditableTableUtil'
import {JEditableTableModelMixin} from '@/mixins/JEditableTableModelMixin'
import {httpAction, putAction} from "@/api/manage";
import {initDictOptions} from "@/components/dict/JDictSelectUtil";

export default {
  name: 'MmStockTransferDetailConfirmTable',
  mixins: [JEditableTableModelMixin],
  components: {},
  data() {
    return {
      loading: false,
      dataSource: [],
      columns: [
        {
          title: '单据号',
          key: 'billNo',
          type: FormTypes.inputNumber,
          width: "120px",
          defaultValue: '',
          disabled: true,
        },
        {
          title: '行号',
          key: 'lineNo',
          type: FormTypes.inputNumber,
          width: "60px",
          defaultValue: '',
          disabled: true,
        },
        {
          title: '物料描述',
          key: 'materialDesc',
          type: FormTypes.input,
          width: "200px",
          defaultValue: '',
          disabled: true,
        },
        {
          title: '单位',
          key: 'unit',
          type: FormTypes.sel_search,
          dictCode: "mdm_unit,unit_name,unit_code",
          width: "80px",
          defaultValue: '',
          disabled: true,
        },
        {
          title: '调拨数量',
          key: 'transferQty',
          type: FormTypes.inputNumber,
          width: "100px",
          placeholder: '请输入${title}',
          defaultValue: '',
          validateRules: [
            {required: true, message: '${title}不能为空'},
            {
              handler(type, value, row, column, callback, target) {
                let {values} = target.getValuesSync({validate: false, rowIds: [row.id]});
                if (type === 'blur' || type === 'getValues') {
                  if (value <= 0) {
                    callback(false, '请输入大于零的数')
                    return;
                  } else if (value > values[0].billQty) {
                    callback(false, '${title}不能超出制单量：' + values[0].billQty)
                    return;
                  } else {
                    callback(true)
                  }
                } else {
                  callback();
                }
              },
            },
          ],
        },
        {
          title: '单价',
          key: 'unitPrice',
          type: FormTypes.inputNumber,
          width: "100px",
          defaultValue: '',
        },
        {
          title: '金额',
          key: 'sumPrice',
          type: FormTypes.inputNumber,
          width: "100px",
          placeholder: '请输入${title}',
          defaultValue: '',
        },
        {
          title: '调入库位',
          key: 'storageLocationIn',
          type: FormTypes.sel_search,
          dictCode: "mdm_storage_location,location_no,id",
          width: "120px",
          placeholder: '请输入${title}',
          defaultValue: '',
          validateRules: [
            {required: true, message: '${title}不能为空'},
            {
              handler(type, value, row, column, callback, target){
                if( type === 'blur' || type === 'getValues'){
                  let {values} = target.getValuesSync({ validate: false, rowIds: [row.id] });
                  let materialBatchFlag = values[0].materialBatchFlag;
                  if(materialBatchFlag === '1' && (value == null || value === '')){
                    callback(false, '${title}不能为空')
                    return
                  }else{
                    callback(true)
                  }
                }else{
                  callback();
                }
              },
            }
          ],
        },
        {
          title: '调入批次',
          key: 'batchIn',
          type: FormTypes.input,
          width: "140px",
          placeholder: '请输入${title}',
          defaultValue: '',
        },
        {
          title: '备注',
          key: 'remark',
          type: FormTypes.input,
          width: "200px",
          placeholder: '请输入${title}',
          defaultValue: '',
        },
        {
          title: '制单数量',
          key: 'billQty',
          type: FormTypes.inputNumber,
          width: "100px",
          defaultValue: '',
          disabled: true,
        },
        {
          title: '调入库房',
          key: 'warehouseIn_dictText',
          type: FormTypes.input,
          width: "120px",
          defaultValue: '',
          disabled: true,
        },
        {
          title: '调出库房',
          key: 'warehouseOut_dictText',
          type: FormTypes.input,
          width: "120px",
          defaultValue: '',
          disabled: true,
        },
        {
          title: '调出库位',
          key: 'storageLocationOut_dictText',
          type: FormTypes.input,
          width: "120px",
          defaultValue: '',
          disabled: true,
        },
        {
          title: '调出批次',
          key: 'batchOut',
          type: FormTypes.input,
          width: "160px",
          defaultValue: '',
          disabled: true,
        },
        {
          title: 'materialId',
          key: 'materialId',
          type: "hidden"
        },
        {
          title: 'materialNo',
          key: 'materialNo',
          type: "hidden"
        },
        {
          title: 'warehouseIn',
          key: 'warehouseIn',
          type: "hidden"
        },
        {
          title: 'warehouseOut',
          key: 'warehouseOut',
          type: "hidden"
        },
        {
          title: 'storageLocationOut',
          key: 'storageLocationOut',
          type: "hidden"
        },
        {
          title: 'pid',
          key: 'pid',
          type: "hidden"
        },
      ],
      url: {
        confirmBatch: "/mm/stockTransfer/confirmDetail",
      }
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
  },
  methods: {
    edit(recordArr){
      this.dataSource = recordArr;
      // 更新库位下拉项
      let storageLocationId = this.columns[7];
      if(recordArr && recordArr[0]['warehouseIn']){
        let warehouseIn = recordArr[0]['warehouseIn']
        let dictCode = "mdm_storage_location,location_no,id" + encodeURIComponent(",enable_flag='1' and warehouse_id='"+ warehouseIn +"'")
        initDictOptions(dictCode).then(res => {
          if (res.success && res.result.length>0) {
            storageLocationId.options = res.result
          } else {
            storageLocationId.options = []
            this.$message.error("未找到库位信息!")
          }
        })
      }else{
        storageLocationId.options = []
      }

    },
    handleOk(){
      let table = this.$refs.mmStockTransferDetail;
      let {error, values} = table.getValuesSync({validate: true})
      if(error === 0){
        //校验通过
        this.loading = true
        let url = this.url.confirmBatch
        putAction(url, values).then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.$emit('ok')
          } else {
            this.$message.warning(res.message)
          }
        }).finally(() => {
          this.loading = false
        })
      }
    },
    qtyAndPriceChange(parm) {
      if (parm && parm['column'] && parm['row'] && parm['target']) {
        let cols = ['transferQty', 'sumPrice', 'unitPrice'];
        let key = parm.column.key;
        if (cols.includes(key)) {
          let editableTable = parm['target'];
          // 重新计算当前行总金额
          if (key === cols[0] || key === cols[2]) {
            let unitPrice = parm.row[cols[2]] || 0;
            let qty = parm.row[cols[0]] || 0;
            let sumPrice = Math.round(unitPrice * qty * 100) / 100;
            editableTable.setValues([{rowKey: parm.row.id, values: {[cols[1]]: sumPrice}}]);
          }
          // 重新计算单价
          if (key === cols[1]) {
            let sumPrice = parm.row[cols[1]] || 0;
            let qty = parm.row[cols[0]] || 0;
            if (qty != 0) {
              let unitPrice = Math.round(sumPrice / qty * 100) / 100;
              editableTable.setValues([{rowKey: parm.row.id, values: {[cols[2]]: unitPrice}}]);
            }
          }
        }
      }
    },
  }
}
</script>

<style scoped>
.action-button {
  margin-bottom: 8px;
}

.gap {
  padding-left: 8px;
}
</style>